package com.leiyuee.mybatis.util;

//import sun.misc.BASE64Decoder;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * HttpRequest实用类
 */
public class RequestUtil {

	/**
	 * 获取当前线程的request
	 * @return
	 */
	public static HttpServletRequest getRequest(){
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		// 获取 request
		return requestAttributes.getRequest();
	}

	public static String getHeaderParam(String name){
		HttpServletRequest request = getRequest();
		return request.getHeader(name);
	}

	public static String getJWT(){
		return getHeaderParam("Authorization");
	}


	/**
	 * 设置Cookie
	 */
	public static void setCookie(HttpServletResponse response, String name,
                                 String value, String path) {
		Cookie cookie = new Cookie(name, value);
		cookie.setSecure(false);
		cookie.setPath(path);
		cookie.setMaxAge(3600 * 24 * 30);

		response.addCookie(cookie);
	}

	/**
	 * 获取一cookie
	 */
	public static Cookie getCookie(HttpServletRequest request, String name) {
		Cookie[] cookies = request.getCookies();
		Cookie returnCookie = null;

		if (cookies == null) {
			return returnCookie;
		}

		for (int i = 0; i < cookies.length; i++) {
			Cookie thisCookie = cookies[i];

			if (thisCookie.getName().equals(name)) {
				if (!thisCookie.getValue().equals("")) {
					returnCookie = thisCookie;
					break;
				}
			}
		}
		return returnCookie;
	}

	/**
	 * 删除cookie
	 */
	public static void deleteCookie(HttpServletResponse response,
                                    Cookie cookie, String path) {
		if (cookie != null) {
			cookie.setMaxAge(0);
			cookie.setPath(path);
			response.addCookie(cookie);
		}
	}

	/**
	 * 获取应用url全路径
	 */
	public static String getAppURL(HttpServletRequest request) {
		StringBuffer url = new StringBuffer();
		int port = request.getServerPort();
		if (port < 0) {
			port = 80;
		}
		String scheme = request.getScheme();
		url.append(scheme);
		url.append("://");
		url.append(request.getServerName());
		if ((scheme.equals("http") && (port != 80))
				|| (scheme.equals("https") && (port != 443))) {
			url.append(':');
			url.append(port);
		}
		url.append(request.getContextPath());
		return url.toString();
	}

	/**
	 * 将 BASE64 编码的字符串 s 进行解码
	 * @param s
	 * @return
	 */
	public static String getFromBASE64(String s) {
		if (s == null) return null;
		try {
			byte[] b = Base64.getDecoder().decode(s);
			return new String(b, StandardCharsets.UTF_8);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 获取请求参数值
	 * @标题:
	 * @描述:
	 * @param request
	 * @param name
	 * @param defaultValue

	 */
	public static String getParameter(HttpServletRequest request, String name,
                                      String defaultValue) {
		String value = request.getParameter(name);
		if (value != null)
			return value;
		else
			return defaultValue;
	}

	/**
	 * 获取请求参数值(并进行编码)
	 * @标题:
	 * @描述:
	 * @param request
	 * @param name
	 * @param defaultValue
	 * @return
	 */
	public static String getParameterDecode(HttpServletRequest request,
											String name, String defaultValue) {

		String value = request.getParameter(name);

		if (value != null) {
			if (CharTools.isUtf8Url(value))
				value = CharTools.Utf8URLdecode(value);
			return value;
		} else
			return defaultValue;
	}

	/**
	 *
	 * @标题:
	 * @描述:
	 * @param request
	 * @param name
	 * @param defaultValue
	 * @param charSet 字符编码
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static String getParameterURLDecode(HttpServletRequest request,
											   String name, String defaultValue, String charSet) {

		String value = request.getParameter(name);

		if(value==null)
			return defaultValue;

		try {
			if (charSet == null) {
				value = java.net.URLDecoder.decode(value);
			} else {
				value = java.net.URLDecoder.decode(value, charSet);
			}
		} catch (Exception e) {
			value = defaultValue;
		}
		return value;
	}

	/**
	 * 获取请求参数值
	 * @标题:
	 * @描述:
	 * @param request
	 * @param name
	 * @return

	 */
	public static String getParameter(HttpServletRequest request, String name) {
		return getParameter(request, name, null);
	}

	/**
	 * 获取int类型请求参数值
	 * @标题:
	 * @描述:
	 * @param request
	 * @param name
	 * @param defaultValue
	 * @return

	 */
	public static int getIntParameter(HttpServletRequest request, String name,
                                      int defaultValue) {
		String paramValue = request.getParameter(name);
		int result = defaultValue;
		if (paramValue != null && !"".equals(paramValue.trim())) {
			try {
				result = Integer.parseInt(paramValue.trim());
			} catch (Exception ignored) {
			}
		}
		return result;
	}

	/**
	 * 获取int类型请求参数值
	 * @标题:
	 * @描述:
	 * @param request
	 * @param name
	 * @return

	 */
	public static int getIntParameter(HttpServletRequest request, String name) {
		return getIntParameter(request, name, 0);
	}

	/**
	 * 获取Integer类型请求参数值
	 * @标题:
	 * @描述:
	 * @param request
	 * @param name
	 * @param defaultValue
	 * @return
	 */
	public static Integer getIntegerParameter(HttpServletRequest request, String name, Integer defaultValue) {
		String paramValue = request.getParameter(name);
		Integer result = defaultValue;
		if (paramValue != null && !"".equals(paramValue.trim())) {
			try {
				result = Integer.parseInt(paramValue.trim());
			} catch (Exception ignored) {
			}
		}
		return result;
	}

	/**
	 * 获取Integer类型请求参数值
	 * @标题:
	 * @描述:
	 * @param request
	 * @param name
	 * @param
	 * @return

	 */
	public static Integer getIntegerParameter(HttpServletRequest request, String name) {
		return getIntegerParameter(request, name, null);
	}

	/**
	 * 获取Long类型请求参数值
	 * @标题:
	 * @描述:
	 * @param request
	 * @param name
	 * @param defaultValue
	 * @return
	 */
	public static Long getLongParameter(HttpServletRequest request, String name, Long defaultValue) {
		String paramValue = request.getParameter(name);
		Long result = defaultValue;
		if (paramValue != null && !"".equals(paramValue.trim())) {
			try {
				result = Long.parseLong(paramValue.trim());
			} catch (Exception ignored) {
			}
		}
		return result;
	}

	/**
	 * 获取Long类型请求参数值
	 * @标题:
	 * @描述:
	 * @param request
	 * @param name
	 * @param
	 * @return
	 */
	public static Long getLongParameter(HttpServletRequest request, String name) {
		return getLongParameter(request, name, null);
	}
	/**
	 * 获取Float类型请求参数值
	 * @标题:
	 * @描述:
	 * @param request
	 * @param name
	 * @param defaultValue
	 * @return

	 */
	public static Float getFloatParameter(HttpServletRequest request, String name, Float defaultValue) {
		String paramValue = request.getParameter(name);
		Float result = defaultValue;
		if (paramValue != null && !"".equals(paramValue.trim())) {
			try {
				result = Float.parseFloat(paramValue.trim());
			} catch (Exception ignored) {
			}
		}
		return result;
	}
	/**
	 * 获取Double类型请求参数值
	 * @标题:
	 * @描述:
	 * @param request
	 * @param name
	 * @param defaultValue
	 */
	public static Double getDoubleParameter(HttpServletRequest request, String name, Double defaultValue) {
		String paramValue = request.getParameter(name);
		Double result = defaultValue;
		if (paramValue != null && !"".equals(paramValue.trim())) {
			try {
				result = Double.parseDouble(paramValue.trim());
			} catch (Exception ignored) {
			}
		}
		return result;
	}
	/**
	 * 获取Float类型请求参数值
	 * @标题:
	 * @描述:
	 * @param request
	 * @param name
	 * @param
	 * @return

	 */
	public static Float getFloatParameter(HttpServletRequest request, String name) {
		return getFloatParameter(request, name, null);
	}
	/**
	 * 获取Short类型请求参数值
	 * @标题:
	 * @描述:
	 * @param request
	 * @param name
	 * @param defaultValue
	 * @return
	 */
	public static Short getShortParameter(HttpServletRequest request, String name, Short defaultValue) {
		String paramValue = request.getParameter(name);
		Short result = defaultValue;
		if (paramValue != null && !"".equals(paramValue.trim())) {
			try {
				result = Short.parseShort(paramValue.trim());
			} catch (Exception ignored) {
			}
		}
		return result;
	}

	/**
	 * 获取Short类型请求参数值
	 * @标题:
	 * @描述:
	 * @param request
	 * @param name
	 * @param
	 * @return

	 */
	public static Short getShortParameter(HttpServletRequest request, String name) {
		return getShortParameter(request, name, null);
	}

	/**
	 * 获取Byte类型请求参数值
	 * @标题:
	 * @描述:
	 * @param request
	 * @param name
	 * @param defaultValue
	 * @return
	 */
	public static Byte getByteParameter(HttpServletRequest request, String name, Byte defaultValue) {
		String paramValue = request.getParameter(name);
		Byte result = defaultValue;
		if (paramValue != null && !"".equals(paramValue.trim())) {
			try {
				result = Byte.parseByte(paramValue.trim());
			} catch (Exception ignored) {
			}
		}
		return result;
	}

	/**
	 * 获取Byte类型请求参数值
	 * @标题:
	 * @描述:
	 * @param request
	 * @param name
	 * @param
	 * @return
	 */
	public static Byte getByteParameter(HttpServletRequest request, String name) {
		return getByteParameter(request, name, null);
	}

	/**
	 * 获取request属性值
	 * @标题:
	 * @描述:
	 * @param request
	 * @param name
	 * @param defaultValue
	 * @return
	 */
	public static Object getAttribute(HttpServletRequest request, String name,
                                      Object defaultValue) {
		Object value = request.getAttribute(name);
		if (value != null)
			return value;
		else
			return defaultValue;
	}

	/**
	 * 获取request属性值
	 * @标题:
	 * @描述:
	 * @param request
	 * @param name
	 * @return
	 */
	public static Object getAttribute(HttpServletRequest request, String name) {
		return getAttribute(request, name, null);
	}

	/**
	 * 获取request中String类型属性值
	 * @标题:
	 * @描述:
	 * @param request
	 * @param name
	 * @param defaultValue
	 * @return
	 */
	public static String getStringAttribute(HttpServletRequest request,
											String name, String defaultValue) {
		Object value = getAttribute(request, name, null);
		if (value == null)
			return defaultValue;
		return (String) value;
	}

	/**
	 * 获取request中String类型属性值
	 * @标题:
	 * @描述:
	 * @param request
	 * @param name
	 * @return
	 */
	public static String getStringAttribute(HttpServletRequest request,
											String name) {
		return getStringAttribute(request, name, null);
	}

	/**
	 * 文本转换为中文全角符号
	 * @标题:
	 * @描述:
	 * @param htmltext
	 * @return
	 */
	public static String textToHtmlValue_ZH(String htmltext) {
		if (htmltext == null || "".equals(htmltext))
			return "";
		String text = htmltext;
		text = htmltext.replaceAll("&", "＆");
		text = text.replaceAll(">", "〉");
		text = text.replaceAll("<", "〈");
		text = text.replaceAll("%", "％");
		text = text.replaceAll("\"", "“").replaceAll("\'", "‘");
		return text;
	}

	/**
	 * 文本转换为html符号
	 * @标题:
	 * @描述:
	 * @param htmltext
	 * @return
	 */
	public static String textToHtml(String htmltext) {
		if (htmltext == null || "".equals(htmltext))
			return "&nbsp;";
		String text = htmltext;
		text = htmltext.replaceAll("&", "&amp;");
		text = text.replaceAll(">", "&gt;");
		text = text.replaceAll("<", "&lt;");
		text = text.replaceAll("%", "&#37;");
		text = text.replaceAll("\"", "&quot;").replaceAll("\'", "&#039;");
		return text;
	}
	public static String textToHtmlTable(String htmltext) {
		if (htmltext == null || "".equals(htmltext))
			return "";
		String text = htmltext;
		text = htmltext.replaceAll("&", "&amp;");
		text = text.replaceAll(">", "&gt;");
		text = text.replaceAll("<", "&lt;");
		text = text.replaceAll("%", "&#37;");
		text = text.replaceAll("\"", "&quot;").replaceAll("\'", "&#039;");
		//text = text.replaceAll("\n", "<br/>").replaceAll("\r", "<br/>");
		text = text.replaceAll("\n", "").replaceAll("\r", "");
		text = text.replaceAll("0x000A", "<br/>");
		return text;
	}

	/**
	 * 文本转换为html符号(html中的value)
	 * @标题:
	 * @描述:
	 * @param htmltext
	 * @return
	 */
	public static String textToHtmlValue(String htmltext) {
		if (htmltext == null || "".equals(htmltext))
			return "";
		String text = htmltext;
		text = htmltext.replaceAll("&", "&amp;");
		text = text.replaceAll(">", "&gt;");
		text = text.replaceAll("<", "&lt;");
		text = text.replaceAll("%", "&#37;");
		text = text.replaceAll("\"", "&quot;").replaceAll("\'", "&#039;");
		text = text.replaceAll("\n", "\\\\n");
		text = text.replaceAll("\r", "\\\\r");
		return text;
	}

	public static String textToHtmlValue2(String htmltext) {
		if (htmltext == null || "".equals(htmltext))
			return "";
		String text = htmltext;
		text = htmltext.replaceAll("&", "&amp;");
		text = text.replaceAll("/", "&#47;");
		text = text.replaceAll(">", "&gt;");
		text = text.replaceAll("<", "&lt;");
		text = text.replaceAll("%", "&#37;");
		text = text.replaceAll("\"", "&quot;").replaceAll("\'", "&#039;");

		text = text.replaceAll("\r\n", "<br/>");//处理sql保存后一个换行保存为两个
		text = text.replaceAll("\n\r", "<br/>");//处理sql保存后一个换行保存为两个

		text = text.replaceAll("\r", "<br/>");
		text = text.replaceAll("\n", "<br/>");
		return text;
	}

	public static String textToHtmlValueExcel(String htmltext) {
		if (htmltext == null || "".equals(htmltext))
			return "";
		String text = htmltext;
		text = htmltext.replaceAll("&", "&amp;");
		text = text.replaceAll("/", "&#47;");
		text = text.replaceAll(">", "&gt;");
		text = text.replaceAll("<", "&lt;");
		text = text.replaceAll("%", "&#37;");
		text = text.replaceAll("\"", "&quot;").replaceAll("\'", "&#039;");
		text = text.replaceAll("\n", "<br/>");
		text = text.replaceAll("\r", "<br/>");
		return text;
	}

	public static String textToJsonValue(String htmltext) {
		if (htmltext == null || "".equals(htmltext))
			return "";
		String text = htmltext;
		text = htmltext.replaceAll("&", "&amp;");
		text = text.replaceAll(">", "&gt;");
		text = text.replaceAll("<", "&lt;");
		text = text.replaceAll("%", "&#37;");
		text = text.replaceAll("\"", "&quot;");
		text = text.replaceAll("\n", "\\\\n");
		text = text.replaceAll("\r", "\\\\r");
		return text;
	}

	/**
	 * 文本转换为html符号(html中的value)
	 * @标题:
	 * @描述:
	 * @param htmltext
	 * @return
	 */
	public static String textToHtmlExtjsValue(String htmltext) {
		if (htmltext == null || "".equals(htmltext))
			return "";
		String text = htmltext;
		text = htmltext.replaceAll("\\\\", "\\\\\\\\");
		text = text.replaceAll(">", "\\\\>");
		text = text.replaceAll("<", "\\\\<");
		text = text.replaceAll("%", "\\\\%");
		text = text.replaceAll("&", "\\\\&");
		text = text.replaceAll("#", "\\\\#");
		text = text.replaceAll("\"", "\\\\\"").replaceAll("\'", "\\\\\'");
		text = text.replaceAll("\n", "\\\\n");
		text = text.replaceAll("\r", "\\\\r");
		return text;
	}

	public static String textToXML(String htmltext) {
		if (htmltext == null || "".equals(htmltext))
			return "";
		String text = htmltext;
		text = htmltext.replaceAll("&", "&amp;");
		text = text.replaceAll("/", "&#47;");
		text = text.replaceAll(">", "&gt;");
		text = text.replaceAll("<", "&lt;");
		text = text.replaceAll("%", "&#37;");
		text = text.replaceAll("\"", "&quot;").replaceAll("\'", "&#039;");
		text = text.replaceAll("\n", "&#10;");
		text = text.replaceAll("\r", "&#10;");
		//text = text.replace(" ", "&nbsp;");
		return text;
	}

	/**
	 * html encode
	 * @标题:
	 * @描述:
	 * @param htmltext
	 * @return
	 */
	public static String textToXML2(String htmltext) {
		if (htmltext == null || "".equals(htmltext))
			return "";
		String text = htmltext;
		text = htmltext.replaceAll("&", "&amp;");
		text = text.replaceAll("/", "&#47;");
		text = text.replaceAll(">", "&gt;");
		text = text.replaceAll("<", "&lt;");
		text = text.replaceAll("%", "&#37;");
		text = text.replaceAll("\"", "&quot;").replaceAll("\'", "&#39;");
		text = text.replaceAll("\n", "&#10;");
		text = text.replaceAll("\r", "&#10;");
		text = text.replaceAll("\\\\", "&#92;");
		text = text.replace(" ", "&nbsp;");
		text = text.replace("+", "&nbsp;");
		return text;
	}
	/**
	 * string to date
	 * @标题:
	 * @描述:
	 * @param time
	 * @param timeFromat
	 * @return
	 */
	public static Date strToDate(String time, String timeFromat)
	{
		if(time==null||time.trim().length()==0)
			return null;
		try {
			DateFormat dateFormat=new SimpleDateFormat(timeFromat);
			return dateFormat.parse(time);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * date to string
	 * @标题:
	 * @描述:
	 * @param time
	 * @param timeFromat
	 * @return
	 */
	public static String dateToStr(Date time, String timeFromat) {
		return dateToStr(time, timeFromat, null);
	}

	public static String dateToStr(Date time, String timeFromat,
								   String defaultValue) {
		try {
			if (time == null)
				return defaultValue;

			DateFormat dateFormat = new SimpleDateFormat(timeFromat);
			return dateFormat.format(time);
		} catch (Exception e) {
			e.printStackTrace();
			return defaultValue;
		}
	}

	/**
	 * 获取请求参数，返回日期
	 * @标题:
	 * @描述:
	 * @param request
	 * @param name
	 * @param timeFromat 转换的日期格式 如：yyyy-MM-dd HH:mm
	 * @return
	 */
	public static Date getDateParameter(HttpServletRequest request, String name, String timeFromat) {
		return getDateParameter(request, name, timeFromat, null);
	}
	/**
	 * 获取请求参数，返回日期
	 * @标题:
	 * @描述:
	 * @param request
	 * @param name
	 * @param timeFromat 转换的日期格式 如：yyyy-MM-dd HH:mm
	 * @param defaultValue 当name的参数值为null时返回的默认值
	 * @return
	 */
	public static Date getDateParameter(HttpServletRequest request, String name, String timeFromat, Date defaultValue) {
		String value = request.getParameter(name);
		Date date = strToDate(value,timeFromat);
		if (date != null)
			return date;
		else
			return defaultValue;
	}

	/**
	 * 获取request中String类型属性值
	 * @标题:
	 * @描述:
	 * @param request
	 * @param name
	 * @param defaultValue
	 * @return
	 */
	public static Boolean getBooleanParameter(HttpServletRequest request,
											  String name, Boolean defaultValue) {
		String paramValue = (String)request.getParameter(name);
		Boolean result= defaultValue;
		if (paramValue == null || paramValue.trim().length()==0)
			return defaultValue;
		try {
			result = Boolean.parseBoolean(paramValue.trim());
		} catch (Exception ignored) {
			result=defaultValue;
		}
		return result;
	}

	/**
	 * 获取request中String类型属性值
	 * @标题:
	 * @描述:
	 * @param request
	 * @param name
	 * @return
	 */
	public static Boolean getBooleanParameter(HttpServletRequest request,
											  String name) {
		return getBooleanParameter(request, name, false);
	}

	public static String StrVoid(String value) {
		return StrVoid(value, "");
	}

	public static String StrVoid(String value, String defaultValue) {
		return value == null ? defaultValue : value;
	}

	public static String StrNull(String value) {
		return StrNull(value, null);
	}

	public static String StrNull(String value, String defaultValue) {
		if (value == null || value.trim().length() <= 0)
			return defaultValue;
		else
			return value.trim();
	}

	/**
	 * 获得map中的Integer
	 * @标题:
	 * @描述:
	 * @param map
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public static Integer getMapInteger(final Map map, final String key,
										final Integer defaultValue) {
		Integer value = (Integer)map.get(key);
		if (value == null)
			return defaultValue;
		return value;
	}

	/**
	 * 获得map中的Date
	 * @标题:
	 * @描述:
	 * @param map
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public static Date getMapDate(final Map map, final String key,
								  final Date defaultValue) {
		Date value = (Date)map.get(key);
		if (value == null)
			return defaultValue;
		return value;
	}

	/**
	 * 获得map中的String
	 * @标题:
	 * @描述:
	 * @param map
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public static String getMapString(final Map map, final String key,
									  final String defaultValue) {
		String value = (String)map.get(key);
		if (value == null)
			return defaultValue;
		return value;
	}


	public static Float getNumberFormat(final Float oldValue, final int decimalDigits){
		return getNumberFormat(oldValue, decimalDigits, null);
	}

	public static Float getNumberFormat(final Float oldValue, final int decimalDigits, final Float defaultValue){
		if(oldValue==null)
			return defaultValue;;

		Float value = null;

		java.text.NumberFormat famatter = java.text.NumberFormat.getNumberInstance(java.util.Locale.CHINA);
		famatter.setMaximumFractionDigits(decimalDigits);

		try {
			value = famatter.parse(famatter.format(oldValue)).floatValue();
		} catch (Exception e) {
			value = defaultValue;
		}

		return value;
	}

	public static String getNumberFormatToStr(final Float oldValue, final int decimalDigits, final String defaultValue){
		if(oldValue==null)
			return defaultValue;;

		String value = null;

		try {
			java.text.NumberFormat famatter = java.text.NumberFormat.getNumberInstance(java.util.Locale.CHINA);
			famatter.setMaximumFractionDigits(decimalDigits);
			value = famatter.format(oldValue);
		} catch (Exception e) {
			value = defaultValue;
		}

		return value;
	}
	/**
	 * 将request请求中的参数以map形式返回
	 * @param request
	 * @return
	 */
	public static Map<String, Object> getRequestParamerterMap(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		@SuppressWarnings("rawtypes")
		java.util.Enumeration enumeration = request.getParameterNames();
		while (enumeration.hasMoreElements()) {
			String paramName = (String) enumeration.nextElement();
			String paramValue = request.getParameter(paramName);
			// 形成键值对应的map
			map.put(paramName, paramValue!=null?paramValue:"");
		}
		return map;
	}
	public static void main(String[] args){
		System.out.println(textToXML2("\\"));
	}
}
